import json
import os

import resources.resource_map.resource_generator as resource_generator
import resources.resource_map.resource_generator_font
import resources.resource_map.resource_generator_js
import resources.resource_map.resource_generator_pbi
import resources.resource_map.resource_generator_pdc
import resources.resource_map.resource_generator_png
import resources.resource_map.resource_generator_raw
import resources.resource_map.resource_generator_vibe

from resources.types.resource_declaration import ResourceDeclaration
from resources.types.resource_definition import StorageType

def _set_prf_required_media_options(bld, resources_dict):
    """
        In case the build variant is PRF, it will also set PRF-required
        options like '"builtin": true'.
    """
    if bld.variant != 'prf':
        return

    for media_item_dict in resources_dict["media"]:
        if media_item_dict["type"] == 'font':
            media_item_dict["extended"] = False
        media_item_dict["builtin"] = True

def _get_resources_dict(bld):
    """
    Takes the common resource_map.json and applies the normal/prf overrides
    to the media definitions.
    """

    def _get_map_dict(bld, node):
        with open(node.abspath(), 'r') as f:
            return json.load(f)

    override_dicts = []
    resource_nodes = []

    common_path = "common/base/resource_map.json"
    common_node = bld.path.find_node(common_path)
    resources_dict = _get_map_dict(bld, common_node)
    resource_nodes.append(common_node)
    common_platform_path = 'common/' + bld.get_platform_name() + '/resource_map.json'

    # handle prf or normal
    is_recovery = (bld.variant == 'prf')
    specific_path = 'prf/base/resource_map.json' if is_recovery else 'normal/base/resource_map.json'
    specific_node = bld.path.find_node(specific_path)
    specific_dict = _get_map_dict(bld, specific_node)
    resource_nodes.append(specific_node)
    override_dicts.append(specific_dict)

    # Add and override resources based on the platform
    root_path = 'normal/'
    if is_recovery:
        root_path = 'prf/'
    platform_path = root_path + bld.get_platform_name() + '/resource_map.json'

    for path in (common_platform_path, platform_path):
        platform_node = bld.path.find_node(path)
        if platform_node:
            platform_dict = _get_map_dict(bld, platform_node)
            resource_nodes.append(platform_node)
            override_dicts.append(platform_dict)

    def update_common_media_item(item_dict):
        name = item_dict["name"]
        for common_media_item in resources_dict["media"]:
            if common_media_item["name"] == name:
                common_media_item.update(item_dict)
                return
        # No existing item found, just append:
        resources_dict["media"].append(item_dict)

    for dict_iter in override_dicts:
        for specific_media_item in dict_iter["media"]:
            update_common_media_item(specific_media_item)

    # Just assign the "files" and "timeline" elements, they cannot exist in the common resource map
    if "files" in specific_dict:
        resources_dict["files"] = specific_dict["files"]

    if "timeline" in specific_dict:
        resources_dict["timeline"] = specific_dict["timeline"]

    # The font scripts expect that the characterList path is absolute, not relative.
    for item in resources_dict["media"]:
        if 'characterList' in item:
            item['characterList'] = \
                            os.path.abspath('resources/' + item['characterList'])

    return resource_nodes, resources_dict

def build(bld):
    # Load up the various resource map json files into a single dictionary
    resource_definition_sources, resources_dict = _get_resources_dict(bld)
    _set_prf_required_media_options(bld, resources_dict)

    resource_definitions = []
    for r in resources_dict['media']:
        defs = resource_generator.definitions_from_dict(bld, r, '')

        resource_definitions.extend(defs)

    resource_declarations = []
    if 'files' in resources_dict:
        for f in resources_dict['files']:
            resource_declarations.extend(ResourceDeclaration(r) for r in f['resources'])

    bld.load('generate_resource_ball ' +
             'generate_builtin ' +
             'generate_fonts ' +
             'generate_pbpack ' +
             'generate_pfs_resources ' +
             'generate_resource_id_header ' +
             'generate_timeline ' +
             'generate_version_header', tooldir='tools/resources/waftools')

    resource_dependencies = resource_definition_sources

    if not bld.capability('HAS_ROCKY_JS') or bld.variant in ('applib', 'test_rocky_emx'):
        # If JS is not enabled, then strip out any js resource objects
        # listed. The resources should be ifdef'ed out in the code
        for r in resource_definitions:
            if r.type == 'js':
                resource_definitions.remove(r)
    elif any((r.type == 'js' for r in resource_definitions)):
        # Make sure our tools for processing js resources are available before processing
        # resources if we have js resources to process
        js_tooling_scripts = [
            bld.path.parent.get_bld().make_node('third_party/jerryscript/jerryscript/js_tooling/{}.js'.
                                                format(script))
            for script in ('generate_snapshot', 'js_tooling')]
        resource_dependencies.extend(js_tooling_scripts)

    # Build the resource ball
    fw_bld_node = bld.bldnode
    resource_ball = fw_bld_node.make_node('system_resources.resball')
    bld(features='generate_resource_ball',
        resources=resource_definitions + bld.DYNAMIC_RESOURCES,
        resource_declarations=resource_declarations,
        resource_dependencies=resource_dependencies,
        resource_ball=resource_ball)

    if bld.variant != 'prf':
        pbpack = fw_bld_node.make_node("system_resources.pbpack")
        bld(features='generate_pbpack',
            resource_ball=resource_ball,
            pbpack_target=pbpack,
            is_system=True)
    else:
        pbpack = None

    bld(features='generate_version_header',
        pbpack=pbpack,
        version_header_target=fw_bld_node.make_node('src/fw/resource/resource_version.auto.h'))

    resource_id_header = fw_bld_node.make_node('src/fw/resource/resource_ids.auto.h')
    bld(features='generate_resource_id_header',
        resource_ball=resource_ball,
        resource_id_header_target=resource_id_header)

    bld(features='generate_builtin',
        resource_ball=resource_ball,
        builtin_target=fw_bld_node.make_node('src/fw/builtin_resources.auto.c'),
        resource_id_header=resource_id_header)

    bld(features='generate_fonts',
        name='generate_fonts',
        resource_ball=resource_ball,
        font_key_header=fw_bld_node.make_node('src/fw/font_resource_keys.auto.h'),
        font_key_table=fw_bld_node.make_node('src/fw/font_resource_table.auto.h'),
        resource_definition_files=resource_definition_sources)

    if bld.variant == '':
        # Build timeline files
        bld(features='generate_timeline',
            name='generate_timeline',
            timeline_dict=resources_dict["timeline"],
            timeline_table_node=fw_bld_node.make_node('src/fw/resource/timeline_resource_table.auto.c'),
            timeline_ids_node=fw_bld_node.make_node('src/fw/resource/timeline_resource_ids.auto.h'),
            layouts_node=bld.path.get_bld().make_node('layouts.json.auto'),
            resource_definition_files=resource_definition_sources)

    if 'files' in resources_dict:
        # Build pfs resource table
        bld(features='generate_pfs_resources',
            name='generate_pfs_resources',
            resource_definition_files=resource_definition_sources,
            pfs_table_node=fw_bld_node.make_node('src/fw/resource/pfs_resource_table.auto.c'),
            file_definitions=resources_dict['files'],
            resource_id_header=resource_id_header)

# vim:filetype=python
